package com.yc.sole.system.biz;

import cn.hutool.core.bean.BeanUtil;
import com.yc.sole.framework.utils.TreeUtil;
import com.yc.sole.system.dto.DeptDto;
import com.yc.sole.system.repository.DeptRepository;
import com.yc.sole.system.request.DeptReq;
import com.yc.sole.system.response.DeptResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2023-03-26
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class DeptBiz {

    private final DeptRepository deptRepository;

    /**
     * 新增
     *
     * @param deptReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveDept(DeptReq deptReq) {
        DeptDto dto = new DeptDto();
        BeanUtil.copyProperties(deptReq, dto);
        deptRepository.saveDept(dto);
    }

    /**
     * 修改
     *
     * @param deptReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDeptById(DeptReq deptReq) {
        DeptDto dto = new DeptDto();
        BeanUtil.copyProperties(deptReq, dto);
        deptRepository.updateDeptById(dto);
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDept(Collection<Long> ids) {
        deptRepository.deleteDeptByIds(ids);
    }

    /**
     * 部门树
     *
     * @return
     */
    public List<DeptResp> selectDeptTree() {
        List<DeptDto> deptList = deptRepository.selectAll();
        return TreeUtil.listToTree(BeanUtil.copyToList(deptList, DeptResp.class));
    }

    /**
     * 部门树
     *
     * @return
     */
    public List<DeptResp> selectAll(DeptReq deptReq) {
        List<DeptDto> deptList = deptRepository.selectDeptTree(deptReq);
        return TreeUtil.listToTree(BeanUtil.copyToList(deptList, DeptResp.class));
    }

    /**
     * 通过Id查询部门
     *
     * @param deptId
     * @return
     */
    public DeptResp selectDeptById(Long deptId) {
        DeptResp deptResp = BeanUtil.copyProperties(deptRepository.selectDeptById(deptId), DeptResp.class);
        if (Objects.isNull(deptResp) || Objects.isNull(deptResp.getParentId())) {
            return deptResp;
        }
        DeptDto deptDto = deptRepository.selectDeptById(deptResp.getParentId());
        if (Objects.nonNull(deptDto)) {
            deptResp.setParentName(deptDto.getDeptName());
        }
        return deptResp;
    }
}
